package bll

import (
	"bytes"
	"jgt-oper/src/model"
	"jgt-oper/src/schema"
	"jgt-oper/src/util"
	"strconv"
	"strings"
	"time"

	"github.com/pkg/errors"
)

// AppVersion 应用版本管理
type AppVersion struct {
	AppVersionModel model.IAppVersion `inject:"IAppVersion"`
}

// QueryPage 查询分页数据
func (a *AppVersion) QueryPage(params schema.AppVersionQueryParam, pageIndex, pageSize uint) (int64, []*schema.AppVersionQueryResult, error) {
	return a.AppVersionModel.QueryPage(params, pageIndex, pageSize)
}

// Get 精确查询数据
func (a *AppVersion) Get(recordID string) (*schema.AppVersion, error) {
	return a.AppVersionModel.Get(recordID)
}

// 解析版本号
func (a *AppVersion) parseVersion(name string) (int64, error) {
	s := bytes.Buffer{}

	vs := strings.Split(name, ".")
	if len(vs) < 3 {
		return 0, errors.New("无效的版本")
	}

	if len(vs) > 3 {
		vs = vs[:3]
	}

	s.WriteString(vs[0])

	for _, v := range vs[1:] {
		if len(v) > 3 {
			v = v[:3]
		}
		s.WriteString(strings.Repeat("0", 3-len(v)))
		s.WriteString(v)
	}

	i, err := strconv.ParseInt(s.String(), 10, 64)
	if err != nil {
		return 0, errors.Wrap(err, "解析版本发生错误")
	}

	return i, nil
}

// Create 创建数据
func (a *AppVersion) Create(item *schema.AppVersion) error {
	version, err := a.parseVersion(item.Name)
	if err != nil {
		return err
	}
	item.Version = version

	exists, err := a.AppVersionModel.CheckDeviceTypeAndVersion(item.DeviceType, item.Version)
	if err != nil {
		return err
	} else if exists {
		return errors.New("版本号已经存在")
	}

	item.ID = 0
	item.RecordID = util.UUID()
	item.Created = time.Now().Unix()
	item.Deleted = 0
	return a.AppVersionModel.Create(item)
}

// Update 更新数据
func (a *AppVersion) Update(recordID string, item *schema.AppVersion) error {
	version, err := a.parseVersion(item.Name)
	if err != nil {
		return err
	}
	item.Version = version

	oldItem, err := a.Get(recordID)
	if err != nil {
		return err
	} else if oldItem == nil {
		return errors.New("无效的数据")
	}

	if !(item.DeviceType == oldItem.DeviceType &&
		item.Version == oldItem.Version) {
		exists, verr := a.AppVersionModel.CheckDeviceTypeAndVersion(item.DeviceType, item.Version)
		if verr != nil {
			return verr
		} else if exists {
			return errors.New("版本号已经存在")
		}
	}

	info := util.StructToMap(item)
	delete(info, "id")
	delete(info, "record_id")
	delete(info, "creator")
	delete(info, "created")
	delete(info, "deleted")
	return a.AppVersionModel.Update(recordID, info)
}

// UpdateStatus 更新状态
func (a *AppVersion) UpdateStatus(recordID string, status int) error {
	info := map[string]interface{}{
		"status": status,
	}
	return a.AppVersionModel.Update(recordID, info)
}

// Delete 删除数据
func (a *AppVersion) Delete(recordID string) error {
	return a.AppVersionModel.Delete(recordID)
}

// CheckUpgrade 检查升级
func (a *AppVersion) CheckUpgrade(deviceType, version string) (map[string]interface{}, error) {
	data := map[string]interface{}{
		"upgrade": 0,
	}

	if deviceType == "" || version == "" {
		return data, nil
	}

	v, err := a.parseVersion(version)
	if err != nil {
		return nil, err
	}

	item, err := a.AppVersionModel.GetUpgradeVersion(deviceType, v)
	if err != nil {
		return nil, err
	}

	if item != nil {
		data["upgrade"] = item.Upgrade
		data["version"] = item.Name
		data["title"] = item.Title
		data["description"] = item.Description
		data["link"] = item.Link
		data["duration"] = item.Duration
	}

	return data, nil
}
